import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:tool/utils/file_utils.dart';
import 'package:uuid/uuid.dart';
import '../../resources.dart';

/// created by hcl
/// on 2025/4/23
/// WelcomePage
/// desc
class WelcomePage extends StatefulWidget {
  const WelcomePage({super.key});

  @override
  State<StatefulWidget> createState() => WelcomePageState();
}

class WelcomePageState extends State<WelcomePage> {
  int index = -1;
  List<String> splashList = [
    ImageUtils.splash1,
    ImageUtils.splash2,
    ImageUtils.splash3,
    ImageUtils.splash4,
    ImageUtils.splash5,
    ImageUtils.splash6,
    ImageUtils.splash7,
    ImageUtils.splash8
  ];

  @override
  void initState() {
    super.initState();
    String hasPermission = GSpUtils.get(GSpUtils.hasPermission);
    String tempAccount = GSpUtils.get(GSpUtils.tempAccount);

    ///如果有权限
    if (hasPermission.isNotEmpty) {
      Directory dir = Directory(uuidDir);

      /// 如果有临时账号
      if (tempAccount.isNotEmpty) {
        File file = File('$uuidDir/$tempAccount');
        if (!file.existsSync()) {
          if (dir.existsSync()) {
            dir.deleteSync();
          }
          dir.createSync(recursive: true);
        }
      } else {
        /// 没有临时账号，但是能找到本地文件，能找回账号
        if (dir.existsSync()) {
          var accountList = dir.listSync();
          if (accountList.isNotEmpty) {
            tempAccount = FileUtils.getFileName(accountList[0].path);
            GSpUtils.set(GSpUtils.tempAccount, tempAccount);
          }
          for (var element in accountList) {
            if (!element.path.contains(tempAccount)) {
              File(element.path).deleteSync();
            }
            break;
          }
        }
      }
    }
    if (tempAccount.isEmpty) {
      tempAccount = const Uuid().v4().replaceAll('-', '');
      GSpUtils.set(GSpUtils.tempAccount, tempAccount);
    }
    Future.delayed(const Duration(milliseconds: 1500), () {
      Nav.pushAndClear(routerName: AppRoutes.main);
    });
  }

  @override
  Widget build(BuildContext context) {
    if (index < 0) {
      index = Random().nextInt(8);
    }
    var content = Container(
      width: designWidth.ss,
      alignment: Alignment.center,
      child: assetImage(splashList[index], fit: BoxFit.fitWidth),
    );
    return Scaffold(
      backgroundColor: ColorUtils.color_FFFFFF,
      body: isWeb
          ? Container(alignment: Alignment.topCenter, child: content)
          : content,
    );
  }
}
